//
//  Group+CoreDataClass.m
//  RecordApp
//
//  Created by chaichai on 2022/3/2.
//
//

#import "Group+CoreDataClass.h"
#import "DataBaseManager.h"
#import "Record+CoreDataClass.h"
#import "NSDate+helper.h"

@implementation Group
+(instancetype)createGroup
{
    Group *obj =
    [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass(self.class) inManagedObjectContext:[DataBaseManager sharedManager].contex];
    
    return obj;
}

+(void)addRecord:(NSDate *)date
{
    NSArray *arr = [Record queryRecord:date];
    Group *gp = nil;
    if (arr && arr.count > 0) {//当天有记录
        Record *obj = arr.lastObject;
        gp = obj.group;
    }else{//当天没有记录
        NSArray *yesterdayArr =
        [Record queryRecord:[date dateByAddingTimeInterval:-24*3600]];
        if (yesterdayArr && yesterdayArr.count > 0) {
            Record *obj = yesterdayArr.lastObject;
            gp = obj.group;
            NSArray *tmrdayArr =
            [Record queryRecord:[date dateByAddingTimeInterval:24*3600]];
            if (tmrdayArr && tmrdayArr.count > 0) {
                Record *tmrObj = tmrdayArr.lastObject;
                Group *gp2 = tmrObj.group;
                gp.last = gp2.last;
                [gp addRecords:gp2.records];
                [DB.contex deleteObject:gp2];
            }else{
                gp.last = date.day;
            }
        }else{
            NSArray *tmrdayArr =
            [Record queryRecord:[date dateByAddingTimeInterval:24*3600]];
            if (tmrdayArr && tmrdayArr.count > 0) {
                Record *obj = tmrdayArr.lastObject;
                gp = obj.group;
                gp.first = date.day;
            }else{
                gp = [self createGroup];
                gp.first = date.day;
                gp.last = date.day;
            }
        }
    }
    gp.count = gp.last - gp.first + 1;
    [gp addRecordsObject:[Record create:date]];
}
@end
